package frames;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/** Implements a frame for 'insert' queries
 * 
 * @author Konstantin Dobrev
 * @version 1.0
 */
public class InsertValuesFrame extends JFrame{
	
	private Connection dbConnection;
	private String dbName;
	private String tableName;
	
	private JLabel [] colNames;
	private String [] colTypes;
	private JTextField [] colValues;
	private JButton insert;
	private JPanel pane;
	
	/** Class constructor
	 * 
	 * @param dbConn represents the established connection to the database
	 * @param database represents the name of the database the user is currently working with
	 * @param table represents the table in which the user will insert records
	 */
	InsertValuesFrame(Connection dbConn, String database, String table) {
		super("Insert values (" + table + ")");
		pane = new JPanel(new GridBagLayout());
		this.add(pane);
		
		dbConnection = dbConn;
		dbName = database;
		tableName = table;
		
		addComponents();
		pack();
		this.setVisible(true);
	}
	
	/**
	 * Initializes all fields depending on the table's columns
	 */
	private void addComponents() {
		try {
			Statement stm = dbConnection.createStatement();
			ResultSet results = stm.executeQuery("SELECT * FROM " + dbName + "." + tableName);
			ResultSetMetaData meta = results.getMetaData();
			int columnCount = meta.getColumnCount();
			colNames = new JLabel[columnCount];
			colValues = new JTextField[columnCount];
			colTypes = new String[columnCount];
			
			GridBagConstraints position = new GridBagConstraints();
			position.anchor = GridBagConstraints.FIRST_LINE_START;
			
			for(int i = 0; i < columnCount; i++) {
				colTypes[i] = meta.getColumnTypeName(i+1);
				
				position.insets = new Insets(9, 9, 9, 9);
				colNames[i] = new JLabel(meta.getColumnName(i+1));
				position.gridx = 0;
				position.gridy = i;
				pane.add(colNames[i], position);
				
				colValues[i] = new JTextField(12);
				position.gridx = 1;
				position.gridy = i;
				pane.add(colValues[i], position);
			}
			insert = new JButton("Insert record");
			insert.addActionListener(new InsertListener());
			position.gridx = 0;
			position.gridy = columnCount;
			pane.add(insert, position);
			
		} catch (SQLException ex) {
			JOptionPane.showMessageDialog(null, ex.getMessage());
		}
	}
	
	
	/** Implements a listener for the 'insert' button
	 * 
	 * @author Konstantin Dobrev
	 * @version 1.0
	 */
	class InsertListener implements ActionListener {

		@Override
		/**
		 * Extracts all the values from the fields, creates the query string
		 * and uses it to insert a new table record
		 */
		public void actionPerformed(ActionEvent arg0) {
			String insertQuery = "INSERT INTO " + tableName + " VALUES (";
			for(int i = 0; i < colValues.length; i++) {
				String dataValue = "";
				if(colTypes[i] == "VARCHAR" || colTypes[i] == "DATE" ||colTypes[i] == "TIME") {
					if(colValues[i].getText().length() == 0) {
						dataValue = "'',";
					}
					else {
						dataValue = "'" + colValues[i].getText() + "',";
					}
				}
				else {
					dataValue = (colValues[i].getText().length() == 0) ? "" : colValues[i].getText() + ",";
				}
				insertQuery += dataValue;
			}
			if(insertQuery.charAt(insertQuery.length()-1) == ',') {
				insertQuery = insertQuery.substring(0, insertQuery.length()-1);
			}
			try {
				Statement stm = dbConnection.createStatement();
				stm.executeUpdate(insertQuery + ")");
				JOptionPane.showMessageDialog(null, "Record inserted to database!");
			} catch (SQLException ex) {
				JOptionPane.showMessageDialog(null, ex.getMessage());
			}
		}
		
	}

}
